package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"net/http"
	"yzy6.26exam/api/request"
	"yzy6.26exam/internal/bao"
	"yzy6.26exam/internal/moble"
	"yzy6.26exam/pkg"
)

func Request(context *gin.Context) {
	var requests request.Request
	if err := context.ShouldBind(&requests); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    204,
			"message": "解析失败",
			"data":    err.Error(),
		})
		return
	}
	var user moble.User
	user.Mobile = requests.Mobile
	err := bao.FindOnce(&user)
	if err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    203,
			"message": "注册失败",
			"data":    err.Error(),
		})
		return
	}
	if user.ID != 0 {
		context.JSON(http.StatusOK, gin.H{
			"code":    202,
			"message": "账号已存在",
			"data":    user.ID,
		})
		return
	}
	password := uuid.NewString()[:16]
	user = moble.User{
		Mobile:    requests.Mobile,
		Password:  pkg.Md5(password),
		Name:      uuid.NewString()[:8] + "用户",
		HeadImage: "",
		Des:       "",
		Sex:       0,
	}
	if err := bao.Create(&user); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    201,
			"message": "注册失败",
			"data":    err.Error(),
		})
		return
	}
	user.Password = password
	context.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "注册成功",
		"data":    user,
	})
}
